import java.util.List;

public class MyLinkList {
    static class ListNode{
        public int val;
        public ListNode prev;
        public ListNode next;
        public ListNode(int val){
            this.val=val;
        }
    }
    public ListNode head;
    //计算个数
    public int size(){
        ListNode cur=head;
        int count=0;
        while (cur!=head){
            count++;
            cur=cur.next;
        }
        return count;
    }
    //打印值
    public void display(){
        ListNode cur=head;
        while (cur!=null){
            System.out.println(cur.val+" ");
            cur=cur.next;
        }
        System.out.println();
    }
    //查询
    public boolean contains(int key){
        ListNode cur=head;
        while (cur!=null){
            if (cur.val==key){
                return true;
            }
            cur=cur.next;
        }
        return false;
    }
    //头插法
    public ListNode last;
    public void addfirst(int data){
        ListNode node =new ListNode(data);
        if (head==null){
            head=node;
            last=node;
        }else {
            node.next=head;
            head.prev=node;
            head=node;
        }
    }
    //尾插法
    public void addLast(int data){
        ListNode node =new ListNode(data);
        if (head==null){
            head=node;
            last=node;
        }else {
            node.prev=last;
            last.next=node;
            last=node;
        }
    }
    //以任意位置插入
    public void addIndex(int index,int data){

        if (head==null){
            addfirst(data);
            return;
        }
        if (index==size()){
            addLast(data);
            return;
        }
        ListNode node=new ListNode(data);
        ListNode cur=head;
        while (index-1!=0){
            cur=cur.next;
        }
        node.next=cur.next;
        cur.next.prev=node;
        cur.next=node;
        node.prev=cur;
    }
    //删除第一次出现的Key节点
    public void remove (int key){
        ListNode cur=head;
        while (cur.val!=key){
            cur=cur.next;
        }
        if (cur==head){
            head=cur.next;
            if (head!=null)//只有一个节点
                head.prev=null;
        }else if(cur==last){
            last=last.prev;
            last.next=null;
        }else {
            cur.prev.next=cur.next;
            cur.next.prev=cur.prev;
        }
    }
    //删除所有为Key的节点
    public void removeAllKey(int key){
        ListNode cur=head;
        while (cur!=null){
            if (cur.val==key){
                if (cur==head){
                    head=head.next;
                    if (head!=null){
                        head.prev=null;
                    }
                }else {
                    cur.prev.next=cur.next;
                    if (cur!=last){
                        cur.next.prev=cur.prev;
                    }else {
                    }
                }
            }
            cur=cur.next;
        }
    }


}
